package wps.mojo.xmlaccess;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.StreamConsumer;

import wps.mojo.utils.ResourceLocator;

/**
 * @Author : <a href="mailto:Juanyong.zhang@carefirst.com">Cham
 *         Juanyong.zhang</a>
 * @Date : Apr 13, 2011
 * @goal execute
 */
public class ExecutorMojo extends AbstractWpsMojo {

	/**
	 * target batch file to be executed
	 * 
	 * @parameter expression="${target}"
	 */
	private String target;

	public void execute() throws MojoExecutionException, MojoFailureException {
		Commandline commandLine = getCommandline();
		executeCmdLine(commandLine);
	}

	private StreamConsumer getStreamConsumer(final String level) {
		StreamConsumer consumer = new StreamConsumer() {
			public void consumeLine(String line) {
				if (level.equalsIgnoreCase("info")) {
					getLog().info(line);
				} else {
					getLog().error(line);
				}
			}
		};

		return consumer;
	}

	private void executeCmdLine(Commandline commandLine)
			throws MojoFailureException {

		try {
			StreamConsumer errConsumer = getStreamConsumer("error");
			StreamConsumer infoConsumer = getStreamConsumer("info");
			int returncode = CommandLineUtils.executeCommandLine(commandLine,
					infoConsumer, errConsumer);
			String logmsg = "Return code: " + returncode;

			if (returncode != 0) {
				throw new MojoFailureException(logmsg);
			} else {
				getLog().info(logmsg);
			}
		} catch (CommandLineException e) {
			throw new MojoFailureException(e.getMessage());
		}

	}

	private Commandline getCommandline() throws MojoFailureException {
		Commandline commandLine = new Commandline();
		try {

			String executable = ResourceLocator.getOnlyFile(workingDirectory,
					target, false).getPath();

			commandLine.setExecutable(executable);
			commandLine.setWorkingDirectory(workingDirectory);
		} catch (Exception e) {
			getLog().error(e.getMessage());
			throw new MojoFailureException("Can't find target executable file:"
					+ target);
		}

		return commandLine;
	}
}
